<template>
    <div>
        <el-card>
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>新增商品</el-breadcrumb-item>
            </el-breadcrumb>
            <el-form :model="productForm" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="商品分类" prop="classifyList">
                    <el-cascader :placeholder="editFlag ? productForm.classifyNameStr : '请选择商品分类'" size="small"
                        v-model="productForm.classifyList" :options="classifyList" :props="props"
                        @change="selectProClassify" @blur="blurHandle"></el-cascader>
                    <i class="el-icon-circle-plus-outline addBtn" @click="addHandle('classify')"></i>
                </el-form-item>
                <el-form-item label="厂商" prop="factor">
                    <el-select size="small" filterable v-model="productForm.factor" placeholder="请选择商品厂商"
                        @change="selectHandle('factor')">
                        <el-option :label="item.factoryName" :value="item.factoryId" v-for="(item, index) in factorList"
                            :key="index"></el-option>
                    </el-select>
                    <i class="el-icon-circle-plus-outline addBtn" @click="addHandle('factor')"></i>
                </el-form-item>
                <el-form-item label="品牌商" prop="brand">
                    <el-select @change="selectHandle('brand')" size="small" v-model="productForm.brand"
                        placeholder="请选择品牌商">
                        <el-option :label="item.brandName" :value="item.brandId" v-for="(item, index) in brandList"
                            :key="index"></el-option>
                    </el-select>
                    <i class="el-icon-circle-plus-outline addBtn" @click="addHandle('brand')"></i>
                </el-form-item>
                <el-form-item label="商品类型" prop="productType">
                    <el-radio-group v-model="productForm.productType">
                        <el-radio label="0">普通商品</el-radio>
                        <el-radio label="1">钻石商品</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品标识" prop="productTag">
                    <el-radio-group v-model="productForm.productTag">
                        <el-radio label="1">常规商品</el-radio>
                        <el-radio label="2">热卖商品</el-radio>
                        <el-radio label="0">滞销商品</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input size="small" v-model="productForm.productName" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="商品副标题" prop="productTitle">
                    <el-input size="small" v-model="productForm.productTitle" placeholder="请输入商品副标题"></el-input>
                </el-form-item>
                <el-form-item label="商品主图">
                    <div class="uploadBox">
                        <div class="imgListBox" v-if="productForm.imageUrl">
                            <div>
                                <el-image :src="productForm.imageUrl" class="avatar"
                                    :previewSrcList="[productForm.imageUrl]"></el-image>
                                <div class="closeBox" @click="delImg(0, 'mainPic')">
                                    <i class="el-icon-circle-close"></i>
                                </div>
                            </div>
                        </div>
                        <el-upload v-else action="aa" class="avatar-uploader" :on-change="proMainChange"
                            :auto-upload="false" accept=".jpg,.png" ref="addProduct_pic" :show-file-list="false">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：尺寸：336*302px，且只能上传jpg/png文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品轮播图">
                    <div class="uploadBox">
                        <div class="imgListBox" v-if="productForm.swiperImgUrl.length != 0">
                            <!-- 编辑商品 -->
                            <template v-if="editFlag">
                                <div v-for="(item, index) in productForm.swiperImgUrl " :key="index">
                                    <el-image :src="item.image" class="avatar"
                                        :previewSrcList="[item.image]"></el-image>
                                    <div class="closeBox" @click="delProImg(item)">
                                        <i class="el-icon-circle-close"></i>
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div v-for="(item, index) in productForm.swiperImgUrl " :key="index">
                                    <el-image :src="item" class="avatar" :previewSrcList="[item]"></el-image>
                                    <div class="closeBox" @click="delImg(index, 'swiper')">
                                        <i class="el-icon-circle-close"></i>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <el-upload action="aa" class="avatar-uploader" :on-change="proSwiperChange" :auto-upload="false"
                            accept=".jpg,.png" ref="addSwiper_pic" :show-file-list="false" multiple>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：尺寸：750*562px，只能上传jpg/png文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品详情图">
                    <div class="uploadBox">
                        <div class="imgListBox" v-if="productForm.detailImgUrl.length != 0">
                            <template v-if="editFlag">
                                <div v-for="(item, index) in productForm.detailImgUrl " :key="index">
                                    <el-image :src="item.image" class="avatar"
                                        :previewSrcList="[item.image]"></el-image>
                                    <div class="closeBox" @click="delProImg(item)">
                                        <i class="el-icon-circle-close"></i>
                                    </div>
                                </div>
                            </template>
                            <template v-else>
                                <div v-for="(item, index) in productForm.detailImgUrl " :key="index">
                                    <el-image :src="item" class="avatar" :previewSrcList="[item]"></el-image>
                                    <div class="closeBox" @click="delImg(index, 'detail')">
                                        <i class="el-icon-circle-close"></i>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <el-upload action="aa" class="avatar-uploader" :on-change="proDetailChange" :auto-upload="false"
                            accept=".jpg,.png" ref="addDetail_pic" :show-file-list="false" multiple>
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：尺寸：图片宽度为750px，只能上传jpg/png文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品视频">
                    <div class="uploadBox">
                        <div class="videoBox" v-if="productForm.productVideoUrl">
                            <div class="closeBox" @click="delImg(0, 'video')">
                                <i class="el-icon-circle-close"></i>
                            </div>
                            <video :src="productForm.productVideoUrl" class="avatar" @click="playVideo">
                            </video>
                            <i class="el-icon-video-play playBtn"></i>
                        </div>
                        <el-upload v-else action="aa" class="avatar-uploader" :on-change="proVideoChange"
                            :auto-upload="false" accept=".mp4" ref="addProduct_pic" :show-file-list="false">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">*注：视频展示在商品详情页的轮播图中，只能上传MP4文件</div>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="商品规格">
                    <div>
                        <el-button size="small" @click="formatHandle('add')">添加规格</el-button>
                        <el-button size="small" @click="formatHandle('del')">删除规格</el-button>
                    </div>
                    <div v-for="(item, index) in  productForm.formatList" :key="index" class="formatBox">
                        <el-checkbox v-model="item.checked" style="margin-top: 16px"></el-checkbox>
                        <div>规格{{ index + 1 }}： <el-input size="small" type="text" v-model="item.formatName"
                                placeholder="请输入规格" />
                        </div>
                        <div>库存： <el-input size="small" type="number" v-model="item.formatKuCun" placeholder="请输入库存" />
                        </div>
                        <div>库存预警： <el-input size="small" type="number" v-model="item.formatYuJing"
                                placeholder="请输入库存阈值" /> </div>
                        <div>价格： <el-input size="small" type="number" v-model="item.formatPrice" placeholder="请输入价格" />
                        </div>
                        <div>邮费： <el-input size="small" type="number" v-model="item.postNum" placeholder="请输入邮费" />
                        </div>
                        <div v-if="productForm.productType == 0">积分： <el-input size="small" type="number"
                                v-model="item.formatPoints" placeholder="请输入所需积分" /> </div>
                        <div v-if="productForm.productType == 1">钻石： <el-input size="small" type="number"
                                v-model="item.formatPoints" placeholder="请输入所需钻石" /> </div>
                        <div>图片：
                            <div class="uploadBox" @click="getIndex(index)">
                                <div class="imgListBox" v-if="item.formatImgUrl">
                                    <div>
                                        <el-image :src="item.formatImgUrl" class="avatar avatar1"
                                            :previewSrcList="[item.formatImgUrl]"></el-image>
                                        <div class="closeBox" @click="delFormat(index)">
                                            <i class="el-icon-circle-close"></i>
                                        </div>
                                    </div>
                                </div>
                                <el-upload v-else action="aa" class="avatar-uploader avatar-uploader1"
                                    :on-change="proFormatChange" :auto-upload="false" accept=".jpg,.png"
                                    ref="addProduct_pic" :show-file-list="false">
                                    <i class="el-icon-plus avatar-uploader-icon avatar-uploader-icon1"></i>
                                </el-upload>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" @click="onSubmit">保存</el-button>
                    <el-button size="small">取消</el-button>
                </el-form-item>
            </el-form>

            <el-dialog title="商品视频" :visible.sync="videoDia" width="30%" :before-close="closeVideo">
                <video :src="productForm.productVideoUrl" autoplay controls class="videoCon"></video>
            </el-dialog>

            <el-dialog title="新增" :visible.sync="addDia" width="30%" :before-close="closeDia">
                <template v-if="addFlag == 'factor'">
                    <el-form :model="factorForm" :rules="factorRules" ref="factor" label-width="100px">
                        <el-form-item label="厂商名称" prop="factoryName">
                            <el-input v-model="factorForm.factoryName" placeholder="请输入厂商名称"></el-input>
                        </el-form-item>
                    </el-form>
                </template>
                <template v-if="addFlag == 'brand'">
                    <el-form :model="brandForm" :rules="brandRules" ref="brand" label-width="100px">
                        <el-form-item label="品牌商名称" prop="brandName">
                            <el-input v-model="brandForm.brandName" placeholder="请输入品牌商名称"></el-input>
                        </el-form-item>
                    </el-form>
                </template>
                <template v-if="addFlag == 'classify'">
                    <el-form :model="classifyForm" :rules="classifyRules" ref="classify" label-width="100px">
                        <el-form-item label="上级分类" prop="classifyValue">
                            <el-select size="small" filterable v-model="classifyForm.classifyValue"
                                placeholder="请选择商品分类">
                                <el-option :label="item.categoryName" :value="item.productCategoryId"
                                    v-for="(item, index) in classifyList" :key="index"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="分类名称">
                            <div>
                                <el-button size="small" @click="nameHandle('add')">添加分类</el-button>
                                <el-button size="small" @click="nameHandle('del')">删除分类</el-button>
                            </div>
                            <div v-for=" (item, index) in classifyForm.classifyNameList" :key="index"
                                style="display: flex;align-items: center;margin-bottom: 16px;">
                                <el-checkbox v-model="item.checked" style="margin-right: 16px"></el-checkbox>
                                <span>分类{{ index + 1 }}：</span>
                                <el-input size="small" v-model="item.cName" placeholder="请输入分类名称"
                                    style="width: 220px;"></el-input>

                                <div class="uploadBox" @click="getClassIndex(index)"
                                    v-if="classifyForm.classifyValue == 0">
                                    <div class="imgListBox" v-if="item.classPicUrl">
                                        <div>
                                            <el-image :src="item.classPicUrl" class="avatar avatar1"
                                                style="margin-left: 16px"
                                                :previewSrcList="[item.classPicUrl]"></el-image>
                                            <div class="closeBox" @click="delClassImg(index)">
                                                <i class="el-icon-circle-close"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <el-upload v-else action="aa" class="avatar-uploader avatar-uploader1"
                                        style="margin-left: 16px" :on-change="imgChange" :auto-upload="false"
                                        accept=".jpg,.png" ref="addProduct_pic" :show-file-list="false">
                                        <i class="el-icon-plus avatar-uploader-icon avatar-uploader-icon1"></i>
                                    </el-upload>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </template>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="closeDia">取 消</el-button>
                    <el-button type="primary" @click="addSubmit">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>

import { addFactory, getFactory } from '../../network/factor'
import { addbrand, getbrand } from '../../network/brand'
import { addCategory, getProductCategory, addFirstCategory } from '../../network/classify'
import { addProduct, getProductById, addImage, deleteImage, updateProduct } from '../../network/product'


export default {
    data() {
        return {
            productForm: {  //  添加商品
                productName: '',
                classifyList: [], // s商品分类
                productType: '0',// 商品类型 0  普通商品  1 钻石商品
                productTitle: '',//商品 副标题
                factor: '',//厂商
                factoryName: '',
                brand: '',//品牌商
                brandName: '',
                productMainPic: '', //主图
                imageUrl: '',//主图路径


                productSwiperList: [],  // 轮播图
                swiperImgUrl: [], // 轮播图路径

                productDetailList: [],  // 详情图
                detailImgUrl: [], // 详情图路径

                productTag: '1',//  商品标识

                productVideo: '', //商品视频
                productVideoUrl: '',  //  商品视频路径

                formatList: [  //商品规格
                    {
                        checked: false,
                        formatName: '',
                        formatKuCun: '',
                        formatYuJing: '',  //  库存预警阈值
                        formatPrice: '',
                        formatPoints: '', // 积分  /钻石
                        formatPic: '',
                        formatImgUrl: '',
						postNum:'',
                    },
                    // {
                    //     checked: false,
                    //     formatName: '200粒/瓶',
                    //     formatKuCun: '600',
                    //     formatYuJing: '30',  //  库存预警阈值
                    //     formatPrice: '50',
                    //     formatPoints: '20', // 积分  /钻石
                    //     formatPic: '',
                    //     formatImgUrl: '',
                    // }
                ],//商品规格
            },
            rules: {
                classifyList: [
                    { required: true, message: '请选择商品分类', trigger: 'change' },
                ],
                productType: [
                    { required: true, message: '请选择商品类型', trigger: 'change' },
                ],
                productTag: [
                    { required: true, message: '请选择商品标识', trigger: 'change' },
                ],
                productName: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                ],
                productTitle: [
                    { required: true, message: '请输入商品副标题', trigger: 'blur' },
                ],
                factor: [
                    { required: true, message: '请选择厂商', trigger: 'change' },
                ],
                brand: [
                    { required: true, message: '请选择品牌商', trigger: 'change' },
                ],
            },

            factorList: [],//厂商
            brandList: [],// 品牌商
            classifyList: [],  //分类列表

            videoDia: false,
            selectFormatIndex: -1,// 上传的规格图片索引


            addFlag: '',//   factor  添加厂商
            addDia: false,// 添加的弹窗、

            factorForm: {
                factoryName: '',
                factoryStatus: 1,
                companyId: sessionStorage.companyId
            },
            factorRules: {
                factoryName: [
                    { required: true, message: '请输入供应商名称', trigger: 'blur' },
                ],
            },
            brandForm: {
                brandName: '',
                brandStatus: 1,
                companyId: sessionStorage.companyId
            },
            brandRules: {
                brandName: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' },
                ],
            },

            classifyForm: {
                classifyNameList: [
                    {
                        cName: '',
                        checked: false,
                        classPic: '',
                        classPicUrl: ''
                    }
                ],
                classifyValue: ''
            },
            classifyRules: {
                classifyName: [
                    { required: true, message: '请输入分类名称', trigger: 'blur' },
                ],
                classifyValue: [
                    { required: true, message: '请选择上级分类', trigger: 'change' },
                ],
            },
            props: {
                expandTrigger: 'hover',
                value: 'productCategoryId',
                label: 'categoryName',
                lazy: true,
                lazyLoad: (node, resolve) => {
                    // console.log(node);
                    const { level } = node;
                    console.log(level);
                    if (level == 1) {
                        this.getChild(node.value).then((res) => {
                            resolve(res);
                        });
                    } else {
                        resolve();
                    }
                },
            },
            // addProps: {
            //     expandTrigger: 'hover',
            //     checkStrictly: true,
            //     value: 'productCategoryId',
            //     label: 'categoryName',
            //     lazy: true,
            //     lazyLoad: (node, resolve) => {
            //         const { level } = node;
            //         console.log(level);
            //         if (level < 3) {
            //             this.getChild(node.value).then((res) => {
            //                 resolve(res);
            //             });
            //         } else {
            //             resolve();
            //         }
            //     },
            // },
            editFlag: false,//  是否为编辑模式
            editProductId: '',//编辑的商品id

            selectClassIndex: -1
        };
    },
    methods: {

        // 上传图片
        imgChange(file) {
            // console.log(index);
            console.log(file);

            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (
                fileType == 'jpg' ||
                fileType == 'png'
            ) {
                this.classifyForm.classifyNameList[this.selectClassIndex].classPicUrl = URL.createObjectURL(file.raw);
                this.classifyForm.classifyNameList[this.selectClassIndex].classPic = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传jpg或png文件')
                return;
            }
        },
        delClassImg(index) {
            this.classifyForm.classifyNameList[index].classPicUrl = ''
            this.classifyForm.classifyNameList[index].classPic = ''
        },
        getClassIndex(index) {
            this.selectClassIndex = index
        },
        getClassifyList() {
            getProductCategory({
                parentId: 0,
                companyId: sessionStorage.companyId,
            }).then(res => {
                if (res.flag) {
                    console.log(res);
                    var list = res.data
                    // 获取一级分类
                    list.forEach((item, index) => {
                        item.children = []
                        item.index = index
                        item.classLevel = 0
                        item.hasChildren = true
                    })
                    this.classifyList = res.data
                    console.log(this.classifyList);
                }
            })

        },
        getChild(id,) {
            return new Promise((resolve) => {
                getProductCategory({
                    parentId: id || 0,
                    companyId: sessionStorage.companyId,
                }).then(res => {
                    if (res.flag) {
                        console.log(res);
                        resolve(res.data);
                    }
                })
            });
        },


        selectHandle(flag) {
            console.log(flag);
            if (flag == 'factor') {
                this.factorList.forEach(ele => {
                    if (ele.factoryId == this.productForm.factor) {
                        this.productForm.factoryName = ele.factoryName
                    }
                })
            } else if (flag == 'brand') {
                this.brandList.forEach(ele => {
                    if (ele.brandId == this.productForm.brand) {
                        this.productForm.brandName = ele.brandName
                    }
                })
            }
        },



        blurHandle(e) {
            console.log(e);
        },






        // 添加商品  选择商品分类
        selectProClassify(value) {
            console.log(value);

            this.productForm.classifyList = value
        },
        selectProClassify1(value) {
            console.log(value);
            this.classifyForm.classifyValue = value
        },


        onSubmit() {
            this.$refs.addForm.validate((valid) => {
                if (!valid) return

                var product = this.productForm,
                    flag = false,
                    formatList = this.productForm.formatList;

                if (product.imageUrl == '') {
                    this.$message.warning('请上传商品主图')
                    return
                }

                if (!this.editFlag) {
                    if (product.productMainPic == '') {
                        this.$message.warning('请上传商品主图')
                        return
                    }
                    if (product.productSwiperList.length == 0) {
                        this.$message.warning('请上传商品轮播图')
                        return
                    }
                    if (product.productDetailList.length == 0) {
                        this.$message.warning('请上传商品详情图')
                        return
                    }
                }
                // if (product.productVideoUrl == '') {
                //     this.$message.warning('请上传商品视频')
                //     return
                // }

                console.log(formatList);

                formatList.forEach(item => {
                    console.log(item);
                    for (var i in item) {
                        if (i != 'formatPic') {
                            flag = item[i] == ''
                        }
                    }
                })
                console.log(flag);
                if (flag) {
                    this.$message.warning('请将商品规格信息填写完整')
                    return
                }



                console.log(product);
                let fd = new FormData();

                fd.append("factoryId", product.factor);
                fd.append("factoryName", product.factoryName);

                fd.append("productBrandId", product.brand);
                fd.append("brandName", product.brandName);

                fd.append("categoryOneId", product.classifyList[0]);
                fd.append("categoryTwoId", product.classifyList[1]);
                fd.append("categoryThreeId", product.classifyList[2] || '0');

                // fd.append("categoryOneName", '');
                // fd.append("categoryTwoName", '');
                // fd.append("categoryThreeName", '');

                fd.append("companyId", sessionStorage.companyId);

                fd.append("productName", product.productName);
                fd.append("productDescription", product.productTitle);

                fd.append("productKind", product.productType);   //商品类型  0 普通商品 1 钻石商品
                fd.append("productSaleType", product.productTag);


                fd.append("maxPrice", product.formatList[0].formatPrice);
                fd.append("maxSource", product.formatList[0].formatPoints);

                // 主图
                fd.append("headImage", product.productMainPic);



                if (!this.editFlag) {
                    // 轮播图
                    product.productSwiperList.forEach((ele, index) => {
                        fd.append(`file`, ele);
                    });
                    // 详情图
                    product.productDetailList.forEach((ele, index) => {
                        fd.append(`files`, ele);
                    });
                }


                // 视频
                fd.append("video", product.productVideo);


                // 商品规格
                product.formatList.forEach((ele, index) => {
                    if (this.editFlag) {
                        fd.append(`productUpdateFormat[${index}].formatId`, ele.formatId || '');

                        fd.append(`productUpdateFormat[${index}].formatName`, ele.formatName);
                        fd.append(`productUpdateFormat[${index}].productNum`, ele.formatKuCun);
                        fd.append(`productUpdateFormat[${index}].productNumWarnimg`, ele.formatYuJing);
                        fd.append(`productUpdateFormat[${index}].productPrice`, ele.formatPrice);
                        fd.append(`productUpdateFormat[${index}].productScore`, ele.formatPoints);
						fd.append(`productFormat[${index}].postNum`, ele.postNum);
                        fd.append(`updateFormatImage${index}`, ele.formatPic);
                        fd.append(`productUpdateFormat[${index}].flag`, ele.formatPic != '' ? index : -1);
                    } else {
                        fd.append(`productFormat[${index}].formatName`, ele.formatName);
                        fd.append(`productFormat[${index}].productNum`, ele.formatKuCun);
                        fd.append(`productFormat[${index}].productNumWarnimg`, ele.formatYuJing);
                        fd.append(`productFormat[${index}].productPrice`, ele.formatPrice);
                        fd.append(`productFormat[${index}].productScore`, ele.formatPoints);
						fd.append(`productFormat[${index}].postNum`, ele.postNum);
                        fd.append("formatImage", ele.formatPic);
                    }
                });

                if (this.editFlag) {
                    // 编辑
                    fd.append("productId", product.productId);
                    updateProduct(fd).then(res => {
                        console.log(res);
                        if (res.flag) {
                            this.$message.success("修改成功");
                            // this.resObjHandle()
                        } else {
                            console.log(res);
                            this.$message.success("修改失败");
                        }
                    });
                } else {
                    addProduct(fd).then(res => {
                        console.log(res);
                        if (res.flag) {
                            this.$message.success("上传成功");
                            // this.resObjHandle()
                        } else {
                            console.log(res);
                            this.$message.success("上传失败");
                        }
                    });
                }



                console.log(this.productForm);
            });
        },

        resObjHandle() {
            this.productForm = {  //  添加商品
                productName: '',
                classifyList: [], // 商品分类
                productType: '0',// 商品类型 0  普通商品  1 钻石商品
                productTitle: '',//商品 副标题
                factor: '',//厂商
                factoryName: '',
                brand: '',//品牌商
                brandName: '',
                productMainPic: '', //主图
                imageUrl: '',//主图路径
                productSwiperList: [],  // 轮播图
                swiperImgUrl: [], // 轮播图路径
                productDetailList: [],  // 详情图
                detailImgUrl: [], // 详情图路径
                productTag: '1',//  商品标识
                productVideo: '', //商品视频
                productVideoUrl: '',  //  商品视频路径
                formatList: [  //商品规格
                    {
                        checked: false,
                        formatName: '',
                        formatKuCun: '',
                        formatYuJing: '',  //  库存预警阈值
                        formatPrice: '',
                        formatPoints: '', // 积分  /钻石
                        formatPic: '',
                        formatImgUrl: '',
                    }
                ]
            }

        },

        beforeUpload(file) {
            console.log(file);
            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

        },

        // 上传主图
        proMainChange(file) {
            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (
                fileType == 'jpg' ||
                fileType == 'png'
            ) {
                this.productForm.imageUrl = URL.createObjectURL(file.raw);
                this.productForm.productMainPic = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传jpg或png文件')
                return;
            }
        },
        // 上传轮播图
        proSwiperChange(file, fileList) {
            console.log(file);
            console.log(fileList);
            // this.productForm.productSwiperList = []
            // this.productForm.swiperImgUrl = []
            fileList.forEach(item => {
                item.fileType = item.name.substring(item.name.lastIndexOf(".") + 1);
                if (
                    item.fileType == 'jpg' ||
                    item.fileType == 'png'
                ) {
                    this.productForm.productSwiperList.push(item.raw)
                    this.productForm.swiperImgUrl.push(URL.createObjectURL(item.raw))
                }
            })


            var flag = fileList.some(item => {
                return item.fileType != 'jpg' && item.fileType != 'png'
            })
            if (flag) {
                this.$message.warning('只能上传jpg或png文件')
            }

            // 编辑模式，直接添加
            if (this.editFlag) {
                this.uploadImg(this.productForm.productSwiperList, 'lunboImage')
            }


            console.log(this.editFlag);

            console.log(flag);

            console.log(fileList);

            this.$refs.addSwiper_pic.clearFiles()
        },

        uploadImg(list, flag) {
            let fd = new FormData();


            fd.append("productId", this.editProductId);


            list.forEach(ele => {
                fd.append(flag, ele);
            });


            addImage(fd).then(res => {
                if (res.flag) {
                    this.$message.success('添加成功')
                    this.getProductInfo(this.editProductId)
                } else {
                    this.$message.warning('添加失败')
                }
            })
        },

        // 上传详情图
        proDetailChange(file, fileList) {
            console.log(file);
            console.log(fileList);
            fileList.forEach(item => {
                item.fileType = item.name.substring(item.name.lastIndexOf(".") + 1);
                if (
                    item.fileType == 'jpg' ||
                    item.fileType == 'png'
                ) {
                    this.productForm.productDetailList.push(item.raw)
                    this.productForm.detailImgUrl.push(URL.createObjectURL(item.raw))
                }
            })

            var flag = fileList.some(item => {
                return item.fileType != 'jpg' && item.fileType != 'png'
            })
            if (flag) {
                this.$message.warning('只能上传jpg或png文件')
            }

            // 编辑模式，直接添加
            if (this.editFlag) {
                this.uploadImg(this.productForm.productDetailList, 'detailImage')
            }

            console.log(flag);
            console.log(fileList);
            console.log(this.productForm.productDetailList);
            console.log(this.productForm.detailImgUrl);

            this.$refs.addDetail_pic.clearFiles()
        },



        // 上传视频
        proVideoChange(file) {
            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (fileType == 'mp4') {
                this.productForm.productVideoUrl = URL.createObjectURL(file.raw);
                this.productForm.productVideo = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传mp4文件')
                return;
            }

            console.log(this.productForm);

        },

        // 上传规格图片
        proFormatChange(file) {
            console.log(file);

            let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
            console.log(fileType);

            if (
                fileType == 'jpg' ||
                fileType == 'png'
            ) {
                this.productForm.formatList[this.selectFormatIndex].formatImgUrl = URL.createObjectURL(file.raw);
                this.productForm.formatList[this.selectFormatIndex].formatPic = file.raw;
            } else {
                // 提醒只能上传的文件类型
                this.$message.warning('只能上传jpg或png文件')
                return;
            }



        },

        getIndex(index) {

            this.selectFormatIndex = index
            console.log(index);
        },

        // 删除选中的图片
        delImg(index, flag) {
            if (flag == 'swiper') {  // 删除轮播图
                this.productForm.productSwiperList.splice(index, 1)
                this.productForm.swiperImgUrl.splice(index, 1)
                this.$refs.addSwiper_pic.clearFiles()
            } else if (flag == 'video') {
                this.productForm.productVideoUrl = ''
                this.productForm.productVideo = ''
            } else if (flag == 'mainPic') {
                this.productForm.imageUrl = ''
                this.productForm.productMainPic = ''
            } else if (flag == 'detail') {
                this.productForm.productDetailList.splice(index, 1)
                this.productForm.detailImgUrl.splice(index, 1)
                this.$refs.addDetail_pic.clearFiles()
            }
        },


        // 删除规格图片
        delFormat(index) {
            this.productForm.formatList[index].formatPic = ''
            this.productForm.formatList[index].formatImgUrl = ''
        },
        // 播放视频
        playVideo() {
            this.videoDia = true
        },
        closeVideo() {
            this.videoDia = false
        },

        // 添加规格  删除规格
        formatHandle(flag) {
            if (flag == 'add') {
                this.productForm.formatList.push({
                    checked: false,
                    formatName: '',
                    formatKuCun: '',
                    formatYuJing: '',  //  库存预警阈值
                    formatPrice: '',
                    formatPoints: '', // 积分
                    formatDiamond: '', //钻石
                    formatPic: '',
                    formatImgUrl: '',
                })
            } else {
                if (this.productForm.formatList.length == 1) {
                    this.$message.warning('最少添加一个规格')
                    return
                }
                var arr = this.productForm.formatList.filter(item => {
                    return item.checked
                })

                console.log(arr);

                if (arr.length == 0) {
                    this.$message.warning('请勾选要删除的规格')
                    return
                }
                this.productForm.formatList = this.productForm.formatList.filter(item => {
                    return !item.checked
                })

            }
        },

        // 添加厂商  品牌商  分类
        addHandle(flag) {
            this.addFlag = flag
            this.addDia = true
            if (flag == 'classify') {
                this.classifyList.unshift({
                    productCategoryId: 0,
                    categoryName: '一级分类'
                },)
            }
        },

        // 关闭新增弹窗
        closeDia() {
            if (this.addFlag == 'factor') {
                this.$refs.factor.resetFields();
            } else if (this.addFlag == 'brand') {
                this.$refs.brand.resetFields();
            } else if (this.addFlag == 'classify') {
                this.$refs.classify.resetFields();
                this.classifyList.shift()
                this.classifyForm = {
                    classifyValue: '',
                    classifyNameList: [
                        {
                            cName: '',
                            checked: false,
                            classPic: '',
                            classPicUrl: ''
                        }
                    ],
                }
            }
            this.addDia = false
        },

        // 添加 确认
        addSubmit() {
            if (this.addFlag == 'factor') {
                this.$refs.factor.validate((valid) => {
                    if (!valid) return

                    console.log(this.factorForm);
                    addFactory(this.factorForm).then(res => {
                        if (res.flag) {
                            console.log(res);
                            this.$message.success('添加成功')
                            this.getFactory()
                            this.closeDia()
                        }
                    })
                });
            } else if (this.addFlag == 'brand') {
                this.$refs.brand.validate((valid) => {
                    if (!valid) return
                    console.log(this.brandForm);
                    addbrand(this.brandForm).then(res => {
                        if (res.flag) {
                            console.log(res);
                            this.$message.success('添加成功')
                            this.getBrand()
                            this.closeDia()
                        }
                    })
                });

            } else if (this.addFlag == 'classify') {

                this.$refs.classify.validate((valid) => {
                    if (!valid) return
                    console.log(this.classifyForm);
                    var flag = false,
                        form = this.classifyForm,
                        list = this.classifyForm.classifyNameList;
                    console.log(form);
                    var parentId = form.classifyValue,
                        categoryNames = '', flag = parentId == 0 ? 0 : 1, isEmpty = false;

                    form.classifyNameList.forEach(ele => {
                        if (ele.classPicUrl == '') {
                            isEmpty = true
                        }
                        if (ele.cName != '') {
                            categoryNames += ele.cName + ','
                        }
                    })

                    console.log(parentId);
                    console.log(categoryNames);
                    console.log(flag);

                    if (categoryNames == '') {
                        this.$message.warning('请输入分类名称')
                        return
                    }
                    if (flag == 0 && isEmpty) {
                        this.$message.warning('请上传分类图片')
                        return
                    }


                    if (flag == 0) {

                        console.log(list);


                        let fd = new FormData();
                        list.forEach((ele, index) => {
                            fd.append(`file`, ele.classPic);
                            fd.append(`categoryList[${index}].categoryName`, ele.cName);
                            fd.append(`categoryList[${index}].categoryStatus`, 1);
                            fd.append(`categoryList[${index}].parentId`, 0);
                            fd.append(`categoryList[${index}].categoryLevel`, 0);
                            fd.append(`categoryList[${index}].companyId`, sessionStorage.companyId);
                        })

                        addFirstCategory(fd).then(res => {
                            if (res.flag) {
                                this.$message.success('添加成功')
                                this.$forceUpdate()
                                this.getClassifyList()
                                this.closeDia()
                            } else {
                                this.$message.warning('添加失败')
                            }
                        })

                    } else if (flag == 1) {
                        addCategory({
                            parentId,
                            categoryNames,
                            flag,
                            companyId: sessionStorage.companyId,
                        }).then(res => {
                            if (res.flag) {
                                this.$message.success('添加成功')
                                this.$forceUpdate()
                                this.getClassifyList()
                                this.closeDia()
                            } else {
                                this.$message.warning('添加失败')
                            }
                        })
                    }
                    console.log(this.form);
                });
            }
        },


        // 获取厂商列表
        getFactory() {
            getFactory({
                factoryName: '',
                CompanyId: sessionStorage.companyId
            }).then(res => {
                if (res.flag) {
                    console.log(res.data);
                    this.factorList = res.data.filter(item => {
                        return item.factoryStatus == 1
                    })
                }
            })
        },
        // 获取品牌商列表
        getBrand() {
            getbrand({
                brandName: '',
                companyId: sessionStorage.companyId
            }).then(res => {
                if (res.flag) {
                    console.log(res.data);
                    this.brandList = res.data.filter(item => {
                        return item.brandStatus == 1
                    })
                }
            })
        },

        // 添加分类名 删除分类名
        nameHandle(flag) {
            if (flag == 'add') {
                this.classifyForm.classifyNameList.push({
                    checked: false,
                    cName: '',
                    classPic: '',
                    classPicUrl: ''
                })
            } else {
                if (this.classifyForm.classifyNameList.length == 1) {
                    this.$message.warning('最少添加一个分类')
                    return
                }
                var arr = this.classifyForm.classifyNameList.filter(item => {
                    return item.checked
                })
                console.log(arr);
                if (arr.length == 0) {
                    this.$message.warning('请勾选要删除的分类')
                    return
                }
                this.classifyForm.classifyNameList = this.classifyForm.classifyNameList.filter(item => {
                    return !item.checked
                })

            }
        },

        // 编辑模式  删除商品图片
        delProImg(obj) {
            console.log(obj);

            this.$confirm('是否删除该图片?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteImage({
                    imageId: obj.imageId
                }).then(res => {
                    if (res.flag) {
                        this.$message.success('删除成功')
                        this.getProductInfo(this.editProductId)
                    } else {
                        this.$message.warning('删除失败')
                    }
                })
            }).catch(() => {

            });
        },


        getProductInfo(id) {
            getProductById({
                productId: id
            }).then(res => {
                if (res.flag) {
                    console.log(res);

                    var pro = res.data;

                    this.productForm = {  //  添加商品
                        productId: pro.productId,
                        productName: pro.productName,
                        classifyNameStr: pro.categoryOneName + '/' + pro.categoryTwoName, // 商品分类
                        classifyList: [pro.categoryOneId, pro.categoryTwoId], // 商品分类
                        productType: pro.productKind + '',// 商品类型 0  普通商品  1 钻石商品
                        productTitle: pro.productDescription,//商品 副标题
                        factor: pro.factoryId,//厂商
                        factoryName: pro.factoryName,
                        brand: pro.productBrandId,//品牌商
                        brandName: pro.brandName,
                        productMainPic: '', //主图
                        imageUrl: pro.productImage,//主图路径
                        productSwiperList: [],  // 轮播图
                        swiperImgUrl: pro.lunboImage, // 轮播图路径
                        productDetailList: [],  // 详情图
                        detailImgUrl: pro.detailImage || [], // 详情图路径
                        productTag: pro.productSaleType + '',//  商品标识
                        productVideo: '', //商品视频
                        productVideoUrl: pro.productVideo,  //  商品视频路径
                        formatList: []
                    }


                    pro.productFormat.forEach(ele => {
                        this.productForm.formatList.push({
                            checked: false,
                            formatId: ele.formatId,
                            formatName: ele.formatName,
                            formatKuCun: ele.productNum,
                            formatYuJing: ele.productNumWarnimg,  //  库存预警阈值
                            formatPrice: ele.productPrice,
                            formatPoints: ele.productScore, // 积分  /钻石
							postNum: ele.postNum,
                            formatPic: '',
                            formatImgUrl: ele.productImage,
                        })
                    })
                }
            })
        },
    },
    created() {
        this.getFactory()
        this.getBrand()
        this.getClassifyList()

        var id = this.$router.currentRoute.query.id;
        if (id) {
            this.editProductId = id
            this.editFlag = true
            this.getProductInfo(id)
        }

    },
    filters: {

    },
};
</script>

<style scoped>
.demo-ruleForm {
    margin-top: 16px;
    height: 78vh;
    overflow-y: scroll;
}

.demo-ruleForm::-webkit-scrollbar {
    display: none;
}

.el-input,
.el-select,
.el-cascader {
    width: 250px;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 8px;
}

.avatar {

    width: 100px;
    height: 100px;
    display: block;
}

.imgListBox,
.uploadBox {
    display: flex;
    align-content: center;
}

.closeBox {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
    height: 20px;
    background-color: rgba(0, 0, 0, .5);
    color: #fff;
    border-radius: 4px;
    cursor: pointer;
    z-index: 10;
}

.playBtn {
    position: absolute;
    top: 34px;
    left: 34px;
    font-size: 32px;
    color: #fff;
}

.imgListBox>div {
    position: relative;
    margin-right: 16px;
}

.el-upload__tip {
    color: red;

}

.videoBox {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
}


.videoCon {
    width: 500px;
    height: 500px;
}

.formatBox {
    display: flex;
    align-items: center;
    width: 100%;

}

.formatBox>div>.el-input {
    width: 150px;
}

.formatBox>div {
    margin: 16px 0 0 16px;
    display: flex;
    align-items: center;
}

.avatar-uploader1,
.avatar-uploader-icon1,
.avatar1 {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
}

.addBtn {
    font-size: 18px;
    margin-left: 16px;
    color: #999;
    cursor: pointer;
}
</style>